import Vue from 'vue'
import VueRouter from 'vue-router'
//引入封装好的仓库模块
import store from '../store'

/* 
  封装一个函数，用来检测你是否含有当前地址的访问权
*/
function hasUrl(path, next) {
  // next()
  // console.log(path, '111111');
  // console.log(JSON.parse(sessionStorage.getItem('userinfo')).menus_url);
  // let result = JSON.parse(sessionStorage.getItem('userinfo')).menus_url.find((item) => {
  //   // console.log(item,'22222222');
  //   return item==path
  // })
  let result = store.state.userinfo.menus_url.find((item)=>item==path)
  if(result){
    next()
  }else{
    next('/home')
  }
}

Vue.use(VueRouter)

export const indexRoutes = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/menu', next)
    },
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/role', next)
    },
  },
  {
    path: '/manger',
    component: () => import('../views/manger/manger.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter: (to, from, next) => {
      hasUrl('/manger', next)
    },
  },
  {
    path: '/cate',
    component: () => import('../views/goodscate/goodscate.vue'),
    meta: {
      title: '商品分类'
    },
  },
  {
    path:"/specs",
    component:()=>import('../views/goodsspecs/goodsspecs.vue'),
    meta:{
      title:"商品规则"
    },
  },
  {
    path:"/goods",
    component:()=>import('../views/goods/goods.vue'),
    meta:{
      title:"商品管理",
    }
  },
];


const routes = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...indexRoutes,
      {
        path: '',
        redirect: '/home'
      },
    ],
  },
  {
    path: '*',
    redirect: '/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//封装一个登录拦截事件，利全局路由导航守卫之前置导航钩子函数
router.beforeEach((to, from, next) => {
  //1.看访问地址是否登录，如果是就next
  if (to.path == '/login') {
    next()
    return
  }
  //2.是否存在登录信息（通过检测是否还有离线存储）
  if (store.state.userinfo) {
    next()
    return
  }
  //3.以上条件都不符合 强制它跳转到登录页
  next('/login')
})



export default router
